﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
//using UtahSIACWebParts.Framework;
using System.Web.UI.WebControls.WebParts;

namespace deFramework.Base
{
    /// <summary>
    /// 
    /// </summary>
    public class BaseWebPart : Microsoft.SharePoint.WebPartPages.WebPart
    {



        #region "Events - Constructor, OnInit, CreateChildControls, OnLoad, Render"

        /// <summary>
        /// 
        /// </summary>
        public BaseWebPart()
        {
            this.ExportMode = WebPartExportMode.All;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            try
            {
                Microsoft.SharePoint.SPWeb currentWeb = Microsoft.SharePoint.SPContext.Current.Web;
                this.MyContext = new deFramework.Common.PresentationContext(ref currentWeb, this);

            }
            catch (Exception exception)
            {
                this.ErrorMessage += string.Format("BaseWebPart Exception: {0} \n\r", exception.ToString());
            }
        }


        /// <summary>
        /// No custom code in this event for the BaseWebPart framework class. 
        /// </summary>
        protected override void CreateChildControls()
        {
            if (this.ErrorMessage.Length == 0)
            {
                try
                {
                    base.CreateChildControls();
                    // No code here 
                }
                catch(Exception ex)
                {
                    this.CurrentException = ex;
                }
            }
        }

        


        /// <summary>
        /// Ensures that the CreateChildControls() is called before events.
        /// Use CreateChildControls() to create your controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            if (this.ErrorMessage.Length == 0)
            {
                base.OnLoad(e);
                this.EnsureChildControls();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        protected override void Render(HtmlTextWriter writer)
        {
            try
            {
                if (this.ErrorMessage.Length == 0) base.Render(writer);

            }
            catch (Exception ex)
            {
                this.ErrorMessage += ex.Message + " " + ex.StackTrace;
            }
            finally
            {
                if (this.ErrorMessage.Length > 0)
                {
                    writer.Write("<p>Framework Web Part Render Error:<br />" + this.ErrorMessage + "</p>");
                }
                //}
            }
            //this.MyContext.Dispose();
        }

        #endregion

        #region "Public - MyContext, ErrMsg"

        /// <summary>
        /// 
        /// </summary>
        public deFramework.Common.PresentationContext MyContext = null;
        
        /// <summary>
        /// 
        /// </summary>
        public string ErrorMessage = String.Empty;

        #endregion

        #region "Polymorphism - PageParamValue, SpWebPropertyValue, SetSpWebProperty, RemoveSpWebProperty"

        /// <summary>
        /// 
        /// </summary>
        /// <param name="aVariableName"></param>
        /// <param name="aDefault"></param>
        /// <returns></returns>
        public string PageParamValue(string aVariableName, string aDefault)
        {
            return this.MyContext.PageParamValue(aVariableName, aDefault);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="aPropertyName"></param>
        /// <param name="aDefault"></param>
        /// <returns></returns>
        public string SpWebPropertyValue(string aPropertyName, string aDefault)
        {
            return this.MyContext.SpWebPropertyValue(aPropertyName, aDefault);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="aPropertyName"></param>
        /// <param name="aValue"></param>
        /// <returns></returns>
        public bool SetSpWebProperty(string aPropertyName, string aValue)
        {
            return this.MyContext.SetSpWebProperty(aPropertyName, aValue);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="aPropertyName"></param>
        /// <returns></returns>
        public bool RemoveSpWebProperty(string aPropertyName)
        {
            return this.MyContext.RemoveSpWebProperty(aPropertyName);
        }


        #endregion

        #region "Polymorphism - MyLog, CurrentException, StandardLog, GotoErrorPage"

        /// <summary>
        /// 
        /// </summary>
        public Common.FrameworkLogging MyLog
        {
            get { return this.MyContext.MyLog; }
        }

        /// <summary>
        /// 
        /// </summary>
        public System.Exception CurrentException
        {
            get
            {
                Exception _ex = null;
                try
                {
                    _ex = this.MyContext.CurrentException;
                }
                catch (Exception ex)
                {
                    _ex = ex;
                }
                return _ex;
            }
            set
            {
                Exception _ex = value;
                try
                {
                    this.MyContext.CurrentException = _ex;
                    if (this.ErrorMessage.Length > 0)
                        this.ErrorMessage = String.Format("{0}; {1}",
                            this.ErrorMessage, _ex.Message);
                    else
                        this.ErrorMessage = _ex.Message;
                }
                catch
                {
                    // do nothing 
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="aMethodName"></param>
        /// <param name="aMessage"></param>
        /// <returns></returns>
        public bool StandardLog(string aMethodName, string aMessage)
        {
            bool _result = false;
            try
            {
                _result = this.MyContext.StandardLog(aMethodName, aMessage);
            }
            catch { }
            return _result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="aTitle"></param>
        /// <param name="aDescription"></param>
        public void GotoErrorPage(string aTitle, string aDescription)
        {
            try
            {
                this.MyContext.GotoErrorPage(aTitle, aDescription);
            }
            catch { }
        }

        #endregion


    }
}



#region "Dead Code"


#region "Properties - LinkToPageUrl, LinkToParamName, IntakeParamName, ExitToPageUrl"

////Reusable Properties for User Controls 


////Design, code and test 4 key properties going from Base Web Part class to any User Control 
////encapsulated: LinkToPageUrl, LinkToParamName, IntakeParamName, CancelToPageUrl properties 
////for Base User Control class. Use/feed certain Session variable(s)??  


///// <summary>
///// 
///// </summary>
//[Personalizable(PersonalizationScope.Shared)]
//[WebBrowsable(true)]
//[System.ComponentModel.Category("Site Integration")]
//[WebDisplayName("Exit To Page Url")]
//[WebDescription("URL that the given presentation object should link to externally upon completion of processing.")]
//public string ExitToPageUrl
//{
//    get
//    {
//        return _ExitToPageUrl;
//    }
//    set
//    {
//        _ExitToPageUrl = value;
//    }
//}
//private string _ExitToPageUrl;



///// <summary>
/////	What page should content be linked into. 
///// </summary>
///// <example>
///// We have a list of categories in a web part and each link needs to go to a 
///// Category details page called ./CategoryDetails.aspx. Thus the property 
///// value will be "CategoryDetails.aspx". 
///// </example>
//[WebBrowsable(true)]
//[Personalizable(PersonalizationScope.Shared)]
//[System.ComponentModel.Category("Site Integration")]
//[WebDisplayName("Link To Page Url")]
//[WebDescription("What page should content be linked into")]
//public string LinkToPageUrl
//{
//    get
//    {
//        return _LinkToPageUrl;
//    }
//    set
//    {
//        _LinkToPageUrl = value;
//        //this.PropertyValueToSessionValue(Mil.Whs.Sharepoint.Ofm.Common.IceConstants.kParamLinkToPageUrl, value); 
//    }
//}
//private string _LinkToPageUrl;



///// <summary>
/////	What param name should content links use for sending forward a param value. 
///// </summary>
///// <example>
///// We have a list of categories in a web part and each link needs to go to a 
///// Category details page with the category id as the parameter value and the 
///// page call is ../CategoryDetails.aspx?myCatId=2201 when the category id is 2201. 
///// Thus the property value for the web part will be "myCatId". 
///// </example>
//[Personalizable(PersonalizationScope.Shared)]
//[WebBrowsable(true)]
//[System.ComponentModel.Category("Site Integration")]
//[WebDisplayName("Link To Param Name")]
//[WebDescription("What param name should content links use for sending forward a param value.")]
//public string LinkToParamName
//{
//    get
//    {
//        return _LinkToParamName;
//    }
//    set
//    {
//        _LinkToParamName = value;
//    }
//}
//private string _LinkToParamName;


///// <summary>
/////	What param name should the user control contained within web part use for finding parameter value.
/////	</summary>
///// <example>
///// We have a list of subcategories in a web part for a certain category and the 
///// user control needs to know which category to use for retrieving the list of subcategories. 
///// The web part page call URL is http://myserver.net/alex.aspx?CategoryIdentifier=4 and thus 
///// the IntakeParamName value is "CategoryIdentifier". If the URL had been http://myserver.net/alex.aspx?id=4 
///// then the IntakeParamName value is "id". 
///// </example>
//[Personalizable(PersonalizationScope.Shared)]
//[WebBrowsable(true)]
//[System.ComponentModel.Category("Site Integration")]
//[WebDisplayName("Intake Param Name")]
//[WebDescription("We have a list of subcategories in a web part for a certain category and the user control needs to know which category to use for retrieving the list of subcategories. The web part page call URL is http://myserver.net/alex.aspx?CategoryIdentifier=4 and thus the IntakeParamName value is 'CategoryIdentifier'. If the URL had been http://myserver.net/alex.aspx?id=4 then the IntakeParamName value is 'id'.")]
//public string IntakeParamName
//{
//    get
//    {
//        return _IntakeParamName;
//    }
//    set
//    {
//        _IntakeParamName = value;
//    }
//}
//private string _IntakeParamName;



#endregion



//if (this._UserControlFullPath.Trim().Length > 0)
//{


//    try
//    {
//        System.Web.UI.Control ctl = this.Page.LoadControl(this._UserControlFullPath);
//        this.Controls.Add(ctl);
//        this._embeddedControl = this.IntegrateEmbeddedControl(ctl);
//    }
//    catch (Exception exception)
//    {
//        this.ErrorMessage += string.Format("{0} failed to load: [[Message]]: {1}\n\r [[Stack Trace]]: {2}", this._UserControlFullPath,
//            exception.ToString(), exception.StackTrace);
//    }
//}
 


//this.PropertyValueToSessionValue(Mil.Whs.Sharepoint.Ofm.Common.IceConstants.kParamIntakeParamName, value); 
//this.PropertyValueToSessionValue(Mil.Whs.Sharepoint.Ofm.Common.IceConstants.kParamCancelToPageUrl, value); 


//this.ErrorMessage = this.UserControlVirtualPath; 

//if (this._UserControlName.Length > 0)
//{
//this.Controls.Clear();
//this.Controls.Add(new LiteralControl(ex.Message));



//private System.Web.UI.UserControl CreateEmbeddedControl(string virtualPathEmbeddedControl)
//{
//    //BaseUserControl _result = (BaseUserControl)
//    System.Web.UI.Control ctl = (System.Web.UI.UserControl)this.Page.LoadControl(virtualPathEmbeddedControl);
//    //ctl.WebPartIndicator = true;
//    //this._embeddedControl.MyContext = this.MyContext;
//    return ctl; 
//}


//this.Controls.Add(this.EmbeddedControl);
//System.Web.UI.Control ctl = (System.Web.UI.UserControl)this.Page.LoadControl(virtualPathEmbeddedControl);




//if (_embeddedControl == null)
//{
//this.UserControlVirtualPath = this._rootControlsDirectory + this._UserControlName;
//this._embeddedControl = this.CreateEmbeddedControl(this._UserControlName);

//this.EmbeddedControl); 
//(BaseUserControl)this.Page.LoadControl(uc);
//}



//private string FullControlPath = "TBD";

//private void SetEmbeddedControlProperties()
//{

//}




//private string UserControlVirtualPath = "unspecified"; 

///// <summary>
///// 
///// </summary>
//protected string RootControlsDirectory
//{
//    set { this._rootControlsDirectory = value; }
//}
//private string _rootControlsDirectory = @"~/_controltemplates/";

/////// <summary>
/////// 
/////// </summary>
//////private string UserControlFullPath
//////{
//    get { return _UserControlFullPath; }
//    set { _UserControlFullPath = value; }
//}

#endregion 